import 'package:sharecommmunit/pages/home/index.dart';
import 'package:sharecommmunit/pages/mine/index.dart';
import 'package:flutter/material.dart';
import 'package:sharecommmunit/utils/eventbus.dart';

import '../utils/token.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  @override
  void initState() {
    super.initState();
    // 先获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    // 2. 订阅事件
     eventBus.on<LogoutEvent>().listen((event) {
      // 跳转登录页面
       Navigator.pushNamed(context, '/login');
     });
  }
  
  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "首页",
      "default": "tabs/home_default.png",
      "active": "tabs/home_active.png",
    },
    {
      "title": "我的",
      "default": "tabs/my_default.png",
      "active": "tabs/my_active.png",
    },
  ];

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
          icon: Image.asset(item['default'], width: 32, height: 32),
          activeIcon: Image.asset(item['active'], width: 32, height: 32),
          label: item['title'],
        ),
      );
    }
    return items;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children:  [HomePage(), MinePage(
              currentIndex: currentIndex,
          )],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
